# -*- coding: utf-8 -*-

from odoo import api, models, fields, _
import xlwt
from odoo.exceptions import Warning, ValidationError
import datetime
from odoo import tools
import math
from io import StringIO
import io
import base64

try:
	import xlwt
except ImportError:
	xlwt = None

EMPTY_MARKER = ''

class js_excel(models.TransientModel):

	_name = 'xls.excel'

	def create_excel(self,ids, model,fields_string,fields_row,selection_field):

		if len(ids) == 0:
			raise ValidationError("请选择要导出的记录！")
		else:
			models = self.env[model].browse(ids)
			workbook = xlwt.Workbook()
			worksheet = workbook.add_sheet('Sheet 1')
			filename = 'Detail Report.xls'
			values = self.env[model].search_read([('id', 'in', ids)], fields_row)
			selection_value = []

			for key in selection_field:
				for value in key:
					selection_value.append(value)

			row = 0
			for lines in fields_string: 
				worksheet.write(0, row, lines, xlwt.easyxf('font:bold on'))
				row += 1

			row_2 = 2
			col_0 = 0
			
			for value in values:
				for lines in fields_row:
					# font_style = xlwt.easyxf("font: name Liberation Sans")
					# font_style = xlwt.easyxf("")
					sql = "SELECT ttype FROM ir_model_fields ir inner join ir_model mo on (ir.model_id = mo.id) WHERE ir.name='%s' and mo.model='%s';" %( str(lines),str(model));
					try:
						self.env.cr.execute(sql)
						[val] = self.env.cr.fetchone()
					except:
						val = None
					if lines:
						if val == 'datetime':
							if value[lines] is False:
								worksheet.write(row_2, col_0, EMPTY_MARKER)
							else:
								date_time = value[lines].strftime('%Y-%m-%d')
								worksheet.write(row_2, col_0, date_time)

						elif val == 'date':
							if value[lines] is False:
								worksheet.write(row_2, col_0, EMPTY_MARKER)
							else:
								date_time = value[lines].strftime('%Y-%m-%d')
								worksheet.write(row_2, col_0, date_time)
												
						elif val == 'selection':
							if value[lines] is False:
								worksheet.write(row_2, col_0, EMPTY_MARKER)
							else:
								for values in selection_value:
									if value[lines] == values[0]:
										worksheet.write(row_2, col_0, values[1])
										break

						elif val == 'many2one' and isinstance(value[lines], tuple):
							if value[lines] is False:
								worksheet.write(row_2, col_0, EMPTY_MARKER)
							else:
								worksheet.write(row_2, col_0, value[lines][1])

						elif val == 'many2many' and isinstance(value[lines], (tuple, list)):
							relation_model = self.env[model]._fields[lines].comodel_name
							many2many_vals = self.env[relation_model].browse(value[lines]).mapped('display_name')
							worksheet.write(row_2, col_0, many2many_vals)
						else:
							if value[lines] is False:
								worksheet.write(row_2, col_0, EMPTY_MARKER)
							else:
								worksheet.write(row_2, col_0, value[lines], )
							
						col_0 += 1
				row_2 += 1
				col_0 = 0

		fp = io.BytesIO()
		workbook.save(fp)
		export_id = self.env['sale.excel'].create({'excel_file': base64.encodestring(fp.getvalue()), 'file_name': filename})
		fp.close()
		return export_id.id


class sale_excel(models.TransientModel):
	_name = "sale.excel"

	excel_file = fields.Binary('Excel报告', readonly=True)
	file_name = fields.Char('Excel文件', size=64)

